package com.caiwangdai.app.ui.home.borrow

import android.support.v7.widget.RecyclerView
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.VirtualLayoutManager
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.HomeContentB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.toast
import com.caiwangdai.app.origin.BaseFragment
import com.caiwangdai.app.ui.home.borrow.list.BannerAdapter
import com.caiwangdai.app.ui.home.borrow.list.ContentAdapter
import kotlinx.android.synthetic.main.fragment_borrow.view.*


class BorrowFragment : BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_borrow

    lateinit var bannerComponent: BannerAdapter
    lateinit var contentComponent: ContentAdapter

    companion object {
        fun newInstance(): BorrowFragment {
             val intent = BorrowFragment()
            return intent
        }
    }


    override fun initView() {
        initVLayout()
        getContentData()
    }



    fun initVLayout() {
        val recy = WMContent.recy_home

        val manager = VirtualLayoutManager(mActivity)
        recy.layoutManager = manager

        val baseAdapter = DelegateAdapter(manager);
        addComponent(baseAdapter)

        recy.adapter = baseAdapter
        // 设置组件复用回收池
        val viewPool = RecyclerView.RecycledViewPool();
        recy.recycledViewPool = viewPool
        viewPool.setMaxRecycledViews(0, 10)
    }


    fun addComponent(baseAdapter: DelegateAdapter) {
        bannerComponent = BannerAdapter(mActivity)
        contentComponent = ContentAdapter(mActivity)

        baseAdapter.addAdapter(bannerComponent)
        baseAdapter.addAdapter(contentComponent)
    }


    //获取内容数据
    fun getContentData() {
        RetrofitHome.getHomeApi()
                .getHomeContent()
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<HomeContentB>(mActivity, WMContent.swipe_refresh) {

                    override fun onSwipeRefresh() {
                        getContentData()
                    }

                    override fun onSuccess(value: NormalResponseB<HomeContentB>) {
                        val info = value.data?.info
                        //updateBanner
                        bannerComponent.setDataToAdapter(info?.banners!!)
                        //updateContent
                        contentComponent.setDataToAdapter(value.data!!)
                    }

                })
    }


}